package io.noties.markwon.app.widget;

import com.noties.markwon.utils.Unit;
import io.noties.markwon.app.utils.KeyEventUtils;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.app.Context;
import ohos.multimodalinput.event.KeyEvent;

/**
 * @author: yangrui
 * @function: TextFieldCustom
 * @date: 2021/3/23
 */
public class TextFieldCustom extends TextField {

    private Unit onBackPressedListener = null;

    void setOnBackPressedListener(Unit onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }

    public TextFieldCustom(Context context, AttrSet attrs) {
        super(context, attrs);

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {

            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                onBackPressedListener = null;
            }
        });
    }

    // TODO YR lack API onKeyPreIme @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (isBoundToWindow()) {
            if (onBackPressedListener != null && hasFocus() && KeyEvent.KEY_BACK == keyCode && KeyEventUtils.isActionUp(event)) {
                onBackPressedListener.action();
            }
        }
        return false;
    }
}
